import {
    CHANGE_BIT_FLAG,
    defaultSksParamColumnData, deleteFromVueVirtualUUID,
    equalsObj,
    findRowInListFromAttrName, generateUUID, getIndexByUUIDTable, initRowVueVirtualUUID,
    isNullOrUndefined,
    mergeFromObject, notNullAndNotUndefined, safeGet, sksParamsPropConfigAvailableValueTypeOptions, strIsEmpty
} from "./core";

export const defaultSksTableColumnData={
    //自定义插槽
    slot: undefined,
    //属性名
    prop: undefined,
    label: undefined,
    clearable: false,
    visible: true,
    minWidth: undefined,
    align: 'center',
    showOverflowTooltip: true,
    className: undefined,
    //不推荐使用
    filters: undefined,

    //页面类型
    //none: 自定义
    htmlType: '',
    //字体颜色
    textColor: 'none',
}

export function loadCacheSksAppPropConfigure({sksAppName}){
    let tmp=localStorage.getItem("sksAppPropConfigure-"+sksAppName)
    let sksAppPropConfigure
    if(isNullOrUndefined(tmp)) {
        sksAppPropConfigure={
            mainSksApp: undefined,
            queryParamsColumnList: [],
            tableColumnList: [],
        }
    }else{
        sksAppPropConfigure=JSON.parse(tmp);
    }
    return sksAppPropConfigure
}

export function loadCacheSksAppPropConfigureSetSksTable({sksAppName,sksTable}){
    let sksAppPropConfigure=loadCacheSksAppPropConfigure({sksAppName})
    sksTable.queryParamsColumnList=sksAppPropConfigure.queryParamsColumnList
    sksTable.tableColumnList=sksAppPropConfigure.tableColumnList
    sksTable.mainSksApp=sksAppPropConfigure.mainSksApp
}

export function autoSaveCacheSksAppPropConfigureAndSetSksTable({sksAppName,sksTable,resData}){
    let sksAppPropConfigure=loadCacheSksAppPropConfigure({sksAppName})
    const tmp={
        mainSksApp: resData.mainSksApp,
        queryParamsColumnList: resData.queryParamsColumnList,
        tableColumnList: resData.tableColumnList,
    }
    if (!equalsObj(tmp, sksAppPropConfigure)) {
        localStorage.setItem("sksAppPropConfigure-"+sksAppName,JSON.stringify(tmp))
        sksTable.queryParamsColumnList=tmp.queryParamsColumnList
        sksTable.tableColumnList=tmp.tableColumnList
        sksTable.mainSksApp=tmp.mainSksApp
    }
}

export function renderTable(mainTable){
    //table 用于触发重新渲染table
    mainTable.showTable=false
    setTimeout(()=>{
        mainTable.showTable=true
    },100)
}

/**
 * 根据列表标签页 重置列表查询的查询参数
 * @param mainTable
 */
export function resetMainTableQueryParamsByTabsFilterValue(mainTable){
    if(mainTable.tabsFilterOptionList&&!isNullOrUndefined(mainTable.tabsFilterValue)){
        let row = findRowInListFromAttrName(mainTable.tabsFilterOptionList,'dictValue',mainTable.tabsFilterValue)
        mergeFromObject(mainTable.queryParams.sksParams,mainTable.tabsSksParamsDefaultSetting,row?.sksParams)
        mainTable.queryParams.mybatisRestrictionName=row?.mybatisRestrictionName
        mainTable.queryParams.virtualOrderByFilterList=mainTable.tabsSksOrderByDefaultSetting
        console.log('handleChangeTabsFilterValueChange.row',row)
        if (row?.virtualOrderByFilterList) {
            mainTable.queryParams.virtualOrderByFilterList=row?.virtualOrderByFilterList
        }
    }
}
export function rowStyleElTable(params){
    const {row,rowIndex}=params
    return rowStyle(params)
}

/**
 * table中根据新增/修改/删除 变色
 * @param row
 * @param rowIndex
 * @return {{}}
 */
export function rowStyle({ row, rowIndex }) {
    let styleJson = {}
    //优先判断删除
    if (row.virtualChangeBitFlag & 4) {
        styleJson = {
            'text-decoration': 'line-through',
            'margin-top': '61px',
            'background-color': '#FFE4B5',
        }
        return styleJson
    }

    if (row.virtualChangeBitFlag & 1) {
        styleJson = {
            'background-color': '#D1EEEE',
        }
    } else if (row.virtualChangeBitFlag & 2) {
        styleJson = {
            'background-color': '#C5C1AA',
        }
    } else {
        styleJson = {}
    }
    // console.log("row=",row)
    // console.log("virtualChangeBitFlag=",row.virtualChangeBitFlag)
    // console.log("styleJson=",styleJson)
    // 返回对象
    return styleJson

}


/**
 *
 * @param data
 *              //时间范围查询
 *              htmlType: `sksFilterParamDateRange`
 useTimeBetween: sksParamColumn({
                                htmlType: `sksFilterParamDateRange`,
                                //根据map中的key为基准
                                // prop: `nameLike`,
                                label: '用餐时间',
                    }),
 * @return {{}}
 */
export function sksParamColumn(data){
    return mergeFromObject({},defaultSksParamColumnData,data,{
            vueVirtualUUID: generateUUID(),
        })
}


/**
 * sksTableQueryFormEl
 *
 * map 形式的查询配置转为 list
 */
export function sksQueryConfigMapToList(sksQueryConfigMap){
    const sksQueryConfigList=[]
    for (let prop of Object.keys(sksQueryConfigMap)) {
        let item = sksParamColumn(sksQueryConfigMap[prop]);
        item.prop=prop
        // console.log("tmp",item)
        sksQueryConfigList.push(item)
    }
    return sksQueryConfigList
}

//对话框可用配置项
export const availableSksWebDialogPropConfig={
    // slot:{
    //     value: undefined,
    //     name: 'slot',
    //     description: '自定义渲染',
    // },
    htmlType: {
        value: '',
        name: 'htmlType',
        description: '控件类型',
        htmlType: 'select',
        htmlTypeOptions:[
            {
                dictValue: '',
                dictLabel: '默认(输入框)'
            },
            {
                dictValue: 'sksText',
                dictLabel: '文本(用于查看)'
            },
            {
                dictValue: 'none',
                dictLabel: '自定义'
            },
            {
                dictValue: 'textarea',
                dictLabel: '文本域'
            },
            // {
            //     dictValue: 'select',
            //     dictLabel: '下拉框'
            // },
            {
                dictValue: 'radio1Yes0No',
                dictLabel: '是否单选(1是0否)'
            },
            {
                dictValue: 'sksRadioDict',
                dictLabel: '字典值单选框'
            },
            // {
            //     dictValue: 'radio',
            //     dictLabel: '单选框'
            // },
            // {
            //     dictValue: 'checkbox',
            //     dictLabel: '复选框'
            // },
            {
                dictValue: 'datetimeYmdhms',
                dictLabel: '日期控件(日期时间)'
            },
            {
                dictValue: 'datetimeYmd',
                dictLabel: '日期控件(日期)'
            },
            {
                dictValue: 'inputPositiveInteger',
                dictLabel: '文本框-正整数'
            },
            {
                dictValue: 'inputInteger',
                dictLabel: '文本框-整数'
            },
            {
                dictValue: 'inputFloat',
                dictLabel: '文本框-浮点型'
            },
            // {
            //     dictValue: 'uploadImage',
            //     dictLabel: '上传控件'
            // },
            {
                dictValue: 'editor',
                dictLabel: '富文本控件'
            },
            // {
            //     dictValue: 'companyCustomer',
            //     dictLabel: '客户'
            // },
            // {
            //     dictValue: 'userItemAppr',
            //     dictLabel: '图纸审核人员'
            // },
            // {
            //     dictValue: 'userMouldDesignAppr',
            //     dictLabel: '模具设计人员'
            // },
            // {
            //     dictValue: 'userProgramWorkshop',
            //     dictLabel: '编程人员'
            // },
            // {
            //     dictValue: 'userCheckWorkshop',
            //     dictLabel: '质检人员'
            // },
            // {
            //     dictValue: 'userProCaseWorkshop',
            //     dictLabel: '铸造人员'
            // },
            {
                dictValue: 'allUser',
                dictLabel: '选择人员'
            },
            {
                dictValue: 'asset',
                dictLabel: '选择设备'
            },
            {
                dictValue: 'storehouse',
                dictLabel: '选择仓库'
            },
            {
                dictValue: 'sksSelectMultipleByLookupController',
                dictLabel: 'LookupController多选'
            },
            {
                dictValue: 'sksSelectSingleByLookupController',
                dictLabel: 'LookupController单选'
            },

        ],
    },
    precision:{
        value: 'defaultPrecision',
        name: 'precision',
        description: '数字类型',
        htmlType: 'select',
        htmlTypeOptions:[
            {
                dictValue: 'defaultPrecision',
                dictLabel: '默认2位'
            },
            {
                dictValue: 'itemQuantityPrecision',
                dictLabel: '物资(销售/采购)小数位数'
            },
            {
                dictValue: 'proQuantityPrecision',
                dictLabel: '工单小数位数'
            },
            {
                dictValue: 'itemLineCostPrecision',
                dictLabel: '物资总金额(行金额)小数位数'
            },

        ]
    },
    ruleType:{
        value: '',
        name: 'ruleType',
        description: '校验类型',
        htmlType: 'select',
        htmlTypeOptions:[
            {
                dictValue: '',
                dictLabel: '无'
            },
            {
                dictValue: 'defaultRequired',
                dictLabel: '默认必填'
            },
            {
                dictValue: 'numberOnlyGreaterThanZero',
                dictLabel: '大于0的数字'
            },
            {
                dictValue: 'numberCanNotLessZero',
                dictLabel: '不能为小于0的数字'
            },
        ]
    },
}

//列表可用配置项
export const availableSksWebListPropPropConfig={
    slot:{
        value: undefined,
        name: 'slot',
        description: '自定义渲染',
    },
    align:{
        value: 'center',
        name: 'align',
        description: '对齐方式',
        htmlType: 'select',
        htmlTypeOptions:[
            {
                dictValue: 'center',
                dictLabel: '居中'
            },
            {
                dictValue: 'left',
                dictLabel: '左对齐'
            },
            {
                dictValue: 'right',
                dictLabel: '右对齐'
            },

        ]
    },
    width:{
        value: undefined,
        name: 'width',
        description: '固定列宽',
    },
    minWidth:{
        value: undefined,
        name: 'minWidth',
        description: '最小列宽',
    },
    htmlType: {
        value: '',
        name: 'htmlType',
        description: '控件类型',
        htmlType: 'select',
        htmlTypeOptions:[
            {
                dictValue: '',
                dictLabel: '默认(字符)'
            },
            {
                dictValue: 'none',
                dictLabel: '自定义'
            },
            {
                dictValue: 'parseTimeYmd',
                dictLabel: '只显示年月日'
            },
            {
                dictValue: 'parseTimeMdHm',
                dictLabel: '只显示月日时分'
            },
            {
                dictValue: 'parseTimeYmdHm',
                dictLabel: '只显示年月日时分'
            },
            {
                dictValue: 'negateNumber',
                dictLabel: '数字取反'
            },
            {
                dictValue: 'absNumber',
                dictLabel: '数字绝对值'
            },
            {
                dictValue: 'dictFormat',
                dictLabel: '显示字典对应的值'
            },
            {
                dictValue: 'dictFormatObject',
                dictLabel: '根据字典对象显示带颜色的字典标签(数据处理需要返回字典对象)'
            },
            {
                dictValue: 'textSysUserId',
                dictLabel: '显示用户ID对应的姓名'
            },
            {
                dictValue: 'no0InfoYes1Danger',
                dictLabel: '加急[0否(灰色)1是(红色)]'
            },
            {
                dictValue: 'unFinish0WarningFinish1Success',
                dictLabel: '0未完结,1完结'
            },
            {
                dictValue: 'formatItemFeature',
                dictLabel: '物资属性'
            },
            {
                dictValue: 'elImageByImgUrl',
                dictLabel: '图片(单字段)'
            },


        ]
    },
    showOverflowTooltip:{
        value: defaultSksTableColumnData.showOverflowTooltip,
        name: 'showOverflowTooltip',
        description: '当内容过长被隐藏时显示 tooltip',
        htmlType: 'select',
        valueType: sksParamsPropConfigAvailableValueTypeOptions.boolean.dictValue,
        htmlTypeOptions:[
            {
                dictValue: true,
                dictLabel: '是'
            },
            {
                dictValue: false,
                dictLabel: '否'
            },
        ]
    },
    //字体颜色
    textColor:{
        value: defaultSksTableColumnData.textColor,
        name: 'textColor',
        description: '字体颜色',
        htmlType: 'select',
        valueType: sksParamsPropConfigAvailableValueTypeOptions.string.dictValue,
        htmlTypeOptions:[
            {
                dictValue: 'none',
                dictLabel: '默认颜色'
            },
            {
                dictValue: 'red',
                dictLabel: '红色'
            },
        ]
    },
}


//查询可用配置项
export const availableSksParamsPropConfig={
    slot:{
        value: undefined,
        name: 'slot',
        description: '自定义渲染',
    },
    labelWidth:{
        value: undefined,
        name: 'labelWidth',
        description: '标签宽度',
    },
    htmlType: {
        value: '',
        name: 'htmlType',
        description: '控件类型',
        htmlType: 'select',
        htmlTypeOptions:[
            {
                dictValue: '',
                dictLabel: '默认输入框'
            },
            {
                dictValue: 'none',
                dictLabel: '自定义'
            },
            {
                dictValue: 'input',
                dictLabel: '文本框'
            },
            // {
            //     dictValue: 'checkboxGroup',
            //     dictLabel: '多选框'
            // },
            {
                dictValue: 'checkbox',
                dictLabel: '勾选框'
            },
            {
                dictValue: 'sksFilterParamStrRangeYm',
                dictLabel: '日期范围(年月-字符串范围搜索)'
            },
            {
                dictValue: 'sksFilterParamDateRange',
                dictLabel: '时间范围(年月日)'
            },
            {
                dictValue: 'sksFilterParamDateRangeYmdhms',
                dictLabel: '时间范围(年月日时分秒)'
            },
            {
                dictValue: 'dictFormat',
                dictLabel: '显示字典对应的值'
            },
            {
                dictValue: 'dateFormatYmd',
                dictLabel: '日期格式化'
            },
            {
                dictValue: 'sksStatusSelect',
                dictLabel: '状态选择'
            },
        ],
    },
    min:{
        value: undefined,
        name: 'min',
        description: '最小值, htmlType=数字形式时有效',
        //如果为空则默认String
        valueType: sksParamsPropConfigAvailableValueTypeOptions.number.dictValue,
        valueTypeOptions:[sksParamsPropConfigAvailableValueTypeOptions.number],
    },
    defaultValue: {
        value: 'undefined',
        name: 'htmlType',
        description: '控件类型',
        htmlType: 'select',
        htmlTypeOptions:[
            {
                dictValue: 'undefined',
                dictLabel: 'undefined'
            },
            {
                dictValue: '',
                dictLabel: '空字符'
            },
            {
                dictValue: '0',
                dictLabel: '数字0'
            },
        ]
    },
    // dictName:{
    //     value: '',
    //     name: 'dictName',
    //     description: '字典名称(控件类型为显示字典值时有效)',
    // hide:()=>{
    // },
    // },
}

export function sksTableColumn(data){
    return mergeFromObject({},defaultSksTableColumnData,data)
}

//显示列表属性名称
export function formatWebListPropConfigDescription(name){
    let tmp=''
    switch (name){
        case 'visible':
            return '是否显示'
        case 'handleDictType':
            return '处理字典类型'
        case 'prop':
            return '属性名'
        case 'label':
            return '标题'
        case 'sksAppId':
            return '配置主键'
        case 'handleValProp':
            return '处理的原属性(为空则使用 prop)'
        case 'handleValType':
            return '数据处理类型'
        default:
            break
    }
    for (let key of Object.keys(availableSksWebListPropPropConfig)) {
        if (name == key) {
            return availableSksWebListPropPropConfig[key].description
        }
    }
    return tmp;
}

// 回显数据字典
export function getDictLabelByVal(datas, value,valueProp="dictValue",labelProp="dictLabel") {
    if (value === undefined) {
        return "";
    }
    var actions = [];
    Object.keys(datas).some((key) => {
        if (datas[key][valueProp] == ('' + value)) {
            actions.push(datas[key][labelProp]);
            return true;
        }
    })
    if (actions.length === 0) {
        actions.push(value);
    }
    return actions.join('');
}

//格式化字典标签
export function dictFormatOnElTableColumn({row, column,mainTable={}}={}){
    // console.log("row",row,column)
    let val = safeGet(row,column.property);
    if(strIsEmpty(val)){
        return val
    }
    let dictTypeConf = findRowInListFromAttrName(mainTable.linkMap.dictTypeConfList||[],'prop',column.property);
    if(isNullOrUndefined(dictTypeConf)){
        console.error("字典信息不存在,prop",column.property)
        return val
    }
    if(isNullOrUndefined(dictTypeConf.dictType)){
        console.error("字典信息不存在,prop",column.property,dictTypeConf)
        return val
    }
    const dictDataMap=mainTable.linkMap.dictDataMap
    if(isNullOrUndefined(dictDataMap)){
        return val
    }
    // console.log("this.dictDataMap",dictDataMap)
    // console.log("this.dictDataMap.type",typeof dictDataMap)
    if(notNullAndNotUndefined(dictDataMap)){
        return getDictLabelByVal(dictDataMap.get(dictTypeConf.dictType),val)
    }
    return val
}

export function addOrUpdateRow({row,mainTable,_this}){
    if(isNullOrUndefined(row.vueVirtualUUID)){
        initRowVueVirtualUUID(row)
    }
    // console.log("mainTable.uniqueId",mainTable.uniqueId)
    if(isNullOrUndefined(row[mainTable.uniqueId])){
        row.virtualChangeBitFlag= CHANGE_BIT_FLAG.add
    }else{
        row.virtualChangeBitFlag= CHANGE_BIT_FLAG.modify
    }
    let index = getIndexByUUIDTable(mainTable.list,row);
    if(index==-1){
        mainTable.list.push(row)
        return;
    }
    _this.$set(mainTable.list, index, row);
}

export function deleteRow({row,mainTable,_this}){
    // console.log("deleteRow",isNullOrUndefined(this.mainTable.uniqueId))
    if(isNullOrUndefined(mainTable.uniqueId)){
        deleteFromVueVirtualUUID(mainTable.list,row)
        console.warn("initMainTableParam() 未返回 uniqueId ")
        return
    }
    // console.log("deleteRow",isNullOrUndefined(row[this.mainTable.uniqueId]))
    if(isNullOrUndefined(row[mainTable.uniqueId])){
        deleteFromVueVirtualUUID(mainTable.list,row.vueVirtualUUID)
    }else{
        //如果启用虚拟删除,则
        if(mainTable.deleteCacheHorizontalLine){
            row.virtualChangeBitFlag= CHANGE_BIT_FLAG.delete
            return;
        }
        deleteFromVueVirtualUUID(mainTable.list,row.vueVirtualUUID)
    }
}
